/**
 * 
 */
package qy.jalgotrade.stratanalyzer.returns;

import com.google.common.math.DoubleMath;

import qy.jalgotrade.utils.CommonUtils;

/**
 * Helper class to calculate time-weighted returns in a portfolio.
 * 
 * Check http://www.wikinvest.com/wiki/Time-weighted_return
 * 
 * @author c-geo
 *
 */
public class TimeWeightedReturns {

	private double __lastValue;

	private double __flows;

	private double __lastPeriodRet;

	private double __cumRet;

	/**
	 * 
	 * @param initialValue
	 */
	public TimeWeightedReturns(double initialValue) {

		__lastValue = initialValue;
		__flows = 0.0;
		__lastPeriodRet = 0.0;
		__cumRet = 0.0;
	}

	public double getCurrentValue() {

		return __lastValue;
	}

	public double getLastPeriodReturns() {

		return __lastPeriodRet;
	}

	/**
	 * Note that this value is not annualized.
	 * 
	 * @return
	 */
	public double getCumulativeReturns() {

		return __cumRet;
	}

	public void deposit(double amount) {

		__flows += amount;
	}

	public void withdraw(double amount) {

		__flows -= amount;
	}

	/**
	 * Update the value of the portfolio.
	 * 
	 * @param currentValue
	 */
	public void update(double currentValue) {

		double retSubperiod;
		if (!Double.isNaN(__lastValue)
		        && !DoubleMath.fuzzyEquals(__lastValue, 0.0, CommonUtils.FUZZY_EQUAL_TOLERANCE_MATH)) {
			retSubperiod = (currentValue - __lastValue - __flows) / __lastValue;
		} else {
			retSubperiod = 0.0;
		}

		__cumRet = (1 + __cumRet) * (1 + retSubperiod) - 1;
		__lastPeriodRet = retSubperiod;
		__lastValue = currentValue;
		__flows = 0.0;
	}
}
